package com.example.demo.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.swing.text.html.parser.Entity;
import java.util.List;

/**
 * Created by Administrator on 2017/6/30.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;




    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ModelAndView loginPage(HttpServletRequest request){
        return new ModelAndView("login");
    }




    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ModelAndView postLogin(HttpServletRequest request,String username,String password){
        //  " admin  "
        EntityWrapper<User> wrapper = new EntityWrapper<User>();
        wrapper.eq("username",username);
        // select * from user where username = ${username} limit 1;
        User user = userService.selectOne(wrapper);
        if(user == null){
            return new ModelAndView("login").addObject("emsg","用户或者密码错误！");
        }
        if(user.getUsername().equals(username.trim()) && user.getPassword().equals(password.trim())){
            request.getSession().setAttribute("username",username);
            return new ModelAndView("redirect:/user/info");
        }else{
            return new ModelAndView("login").addObject("emsg","用户或者密码错误！");
        }
    }

    @RequestMapping(value = "/info",method = RequestMethod.GET)
    public ModelAndView info(HttpServletRequest request){
        String username  = (String )request.getSession().getAttribute("username");
        EntityWrapper<User> wrapper = new EntityWrapper<User>();
        wrapper.eq("username",username);
        // select * from user where username = ${username} limit 1;
        User user = userService.selectOne(wrapper);

        return new ModelAndView("info").addObject("username",username).addObject("user",user);
    }

    @RequestMapping(value = "/info",method = RequestMethod.POST)
    public ModelAndView postInfo(HttpServletRequest request){
        return new ModelAndView("");
    }


    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public ModelAndView getUsers(HttpServletRequest request){

        List<User> userList = userMapper.selectPage(
                new Page<User>(1, 10),
                new EntityWrapper<User>()
        );
        return new ModelAndView("users").addObject("userList",userList);
    }


}
